package com.atguigu.lease.web.admin.custom.convert;

import com.atguigu.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

/**
 * @Author :冉佳
 * @CreateTime: 2025-02-06
 * @Description:
 * @Version:1.0
 **/
// 自定义消息转换器 将前端转递的字符类型的参数转化为相应的枚举类型
// 该方法比较好 一劳永逸
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {

        return new Converter<String, T>() {
            @Override
            public T convert(String source) {
                for (T enumConstant : targetType.getEnumConstants()) {
                    if(source.equals(String.valueOf(enumConstant.getCode()))){
                        return enumConstant;
                    }
                }
                return null;
            }
        };
    }
}
